/*
 * @Description: vscode自带注释
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-04-11 11:29:47
 * @LastEditors: lhl
 * @LastEditTime: 2021-04-11 12:11:08
 */

import { createI18n } from 'vue-i18n'
import { getLanguage } from '../utils/cookies'

// Vant built-in lang
import { Locale } from 'vant'
import enUS from 'vant/es/locale/lang/en-US'
import zhCN from 'vant/es/locale/lang/zh-CN'
import zhTW from 'vant/es/locale/lang/zh-TW'
import jaJP from 'vant/es/locale/lang/ja-JP'

// User defined lang
import enUsLocale from './en_US/index'
import zhCnLocale from './zh_CN/index'
import zhTwLocale from './zh_TW/index'
import jaJpLocale from './ja_JP/index'

const messages: any = {
  'zh-CN': {
    ...zhCN,
    ...zhCnLocale
  },
  'zh-TW': {
    ...zhTW,
    ...zhTwLocale
  },
  'en-US': {
    ...enUS,
    ...enUsLocale
  },
  'ja-JP': {
    ...jaJP,
    ...jaJpLocale
  }
}

export const getLocale = () => {
  const cookieLanguage = getLanguage()
  if (cookieLanguage) {
    document.documentElement.lang = cookieLanguage
    return cookieLanguage
  }

  const language = navigator.language.toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale
      return locale
    }
  }

  // Default language is english
  return 'en-US'
}

const CURRENT_LANG = getLocale()
// first entry
Locale.use(CURRENT_LANG, messages[CURRENT_LANG])

const i18n = createI18n({
  locale: CURRENT_LANG,
  messages
})

export default i18n
